#define _CRT_SECURE_NO_WARNINGS 1
#include"heap.h"
void Inite(Heap* p) {
	p->a = NULL;
	p->capacity = p->size = 0;



}
void Push(Heap* php, HeapType x)
{
	assert(php);

	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HeapType* tmp = (HeapType*)realloc(php->a, newcapacity * sizeof(HeapType));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}

		php->a = tmp;
		php->capacity = newcapacity;
	}

	php->a[php->size] = x;
	php->size++;

	AdjustUp(php->a, php->size - 1);
}
void Pop(Heap* p) {
	Swap(&p->a[0], &p->a[p->size - 1]);
	


	p->size--;
	AdjustDown(p->a, 0, p->size);


}
bool Empty(Heap* p) {
	return p->size == 0;


}
HeapType Top(Heap* p) {

	return p->a[0];

}
void Print(Heap* p) {
	{
		while (!Empty(p))
		{
			printf("%d ", Top(p));
			Pop(p);
		}

	}
}
void Swap(HeapType *a, HeapType *b) {
	 
	HeapType* tem =*a;
	*a = *b;
	*b = tem;

}
void AdjustUp(HeapType* a, int child) {
	int parent = (child - 1) / 2;
	while (child > 0) {
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;

		}
		
		else
		{
			break;
		}

	}


}
void AdjustDown(HeapType* a, int parent, int n) {
	int child = parent * 2 + 1;
	while(child<n)
		{ 
			if (child+1<n&&a[child] > a[child + 1]) {
		child = child + 1;

			
	}
			if (a[parent] > a[child]) {
				Swap(&a[parent], &a[child]);
				parent = child;
				child = child * 2 + 1;
			}
			else
			{
				break;
			}
	
		}

}

